package com.zjsru.payment.service.Impl;

import com.zjsru.payment.clients.OrderClient;
import com.zjsru.payment.clients.ProductClient;
import com.zjsru.payment.mapper.PaymentMapper;
import com.zjsru.payment.pojo.ProductTransaction;
import com.zjsru.payment.service.PaymentService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Resource
    private PaymentMapper paymentMapper;

    @Resource
    private OrderClient orderClient;
    @Resource
    private ProductClient productClient;

    @Override
    public void createTransaction(ProductTransaction productTransaction) {
        if (productTransaction.getProductId()<0){
            throw new RuntimeException("参数错误");
        }
        productClient.updateProductCount(productTransaction.getProductNum(), productTransaction.getProductId());
        orderClient.updateOrderStatus(productTransaction.getOrderId());
        productTransaction.setCreateTime(LocalDateTime.now());
        productTransaction.setUpdateTime(LocalDateTime.now());
        paymentMapper.createTransaction(productTransaction);
    }

    @Override
    public List<ProductTransaction> queryTransaction() {

        return paymentMapper.queryTransaction();
    }

    @Override
    public List<ProductTransaction> queryTransactionByUserId(Long userId) {
        return paymentMapper.queryTransactionByUserId(userId);
    }

    @Override
    public void refund(Long transactionId) {

        ProductTransaction productTransaction = paymentMapper.queryTransactionById(transactionId);
        if (productTransaction == null){
            throw new RuntimeException("未找到该交易记录");
        }
        Integer productNum = -productTransaction.getProductNum();
        productClient.updateProductCount(productNum,productTransaction.getProductId());

        paymentMapper.refund(transactionId);
    }
}
